package com.jtw.common.util;

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class DES3 {
	
	public static void main(String[] args) {
		System.out.println(encrypt("221892603c1d2205c42e4b46"));
	}

	private static final String Algorithm = "DESede";

	public static String decrypt(String value) {
		byte[] b = decryptMode(GetKeyBytes(), Base64.decode(value));
		return new String(b);
	}

	public static String encrypt(String value) {
		String str = Base64.encode(encryptMode(GetKeyBytes(), value.getBytes()));
		return str;
	}

	// 计算24位长的密码byte值,首先对原始密钥做MD5算hash值，再用前8位数据对应补全后8位
	public static byte[] GetKeyBytes() {
		byte[] bkey24 = new byte[24];
		try {
			java.security.MessageDigest alg = java.security.MessageDigest.getInstance("MD5");
			alg.update(Algorithm.getBytes());
			byte[] bkey = alg.digest();
			int start = bkey.length;
			for (int i = 0; i < start; i++) {
				bkey24[i] = bkey[i];
			}
			for (int i = start; i < 24; i++) {
				bkey24[i] = bkey[i - start];
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return bkey24;
	}

	public static byte[] encryptMode(byte[] keybyte, byte[] src) {
		try {
			// 生成密钥
			SecretKey deskey = new SecretKeySpec(keybyte, Algorithm);
			Cipher c1 = Cipher.getInstance(Algorithm);
			c1.init(Cipher.ENCRYPT_MODE, deskey);
			return c1.doFinal(src);
		} catch (Exception e1) {
			
		}
		return null;
	}

	public static byte[] decryptMode(byte[] keybyte, byte[] src) {
		try {
			SecretKey deskey = new SecretKeySpec(keybyte, Algorithm);
			Cipher c1 = Cipher.getInstance(Algorithm);
			c1.init(Cipher.DECRYPT_MODE, deskey);
			return c1.doFinal(src);
		} catch (Exception e) {
			
		}
		return null;
	}

	// 转换成十六进制字符串
	public static String byte2hex(byte[] b) {
		String hs = "";
		String stmp = "";
		for (int n = 0; n < b.length; n++) {
			stmp = (Integer.toHexString(b[n] & 0XFF));
			if (stmp.length() == 1)
				hs = hs + "0" + stmp;
			else
				hs = hs + stmp;
			if (n < b.length - 1)
				hs = hs + ":";
		}
		return hs.toUpperCase();
	}
}
